import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

// 让vue框架应用vuex
Vue.use(Vuex)
export default ({
    state: {
        // 定义属性
        bestHouse: [],
        houseTotal: 0, //数组总数
        house: {}
    },
    mutations: {
        // 给上面设置的属性变量设置
        //这里的方法，组件也可以调用
        setBestHouse(state, val) {
            //通过这个方法，修改bestHouse的值
            state.bestHouse = state.bestHouse.concat(val);
            //console.log(val)
        },
        clearBestHouse(state) {
            state.bestHouse = []
        }
    },
    actions: {
        // 定义方法
        getBestHouse({
                commit,
                state
            },
            pn) {
            // pn 页码，默认是第1页
            // console.log(pn);
            let start = (pn - 1) * 3; // 0 3 6 9
            let end = start + 3; // 3 6 9 12
            axios({
                method: 'get',
                url: '/data/house_data.json?pn=1'
            }).then((res) => {
                // console.log(res.data)
                let data = res.data
                    // console.log(data)
                if (data.code === 200) { //判断状态值是否等于200
                    commit('setBestHouse', data.bestHouse.slice(start, end)); // 调用上面mutations属性的方法setBestHouse
                    // console.log(state.bestHouse)
                    state.houseTotal = data.bestHouse.length
                }
            }).catch((err) => {
                console.log(err)
            })
        },
        getOneHouse({
            state
        }, hid) {
            axios({
                method: 'get',
                url: '/data/house_data.json'
            }).then((res) => {
                let data = res.data;
                if (data.code === 200) {
                    //模拟数据
                    let house = {}
                    let bestHouse = data.bestHouse //获取全部房源，数组
                        // console.log(houses)
                        // console.log(houses[0].hid)
                        // console.log(typeof (data.bestHouse))

                    bestHouse.forEach((v) => {
                        if (v.hid === parseInt(hid)) {
                            house = v; // 把对应那个房源的值，赋值给house
                        }
                    });
                    // console.log(house);
                    state.house = house;
                }
            }).catch({

            })
        }
    },
    modules: {

    }
})